package test.design_pattern.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//目标类接口
interface IDog {
    void run();
}

//目标类
class GunDog implements IDog {

    @Override
    public void run() {
        System.out.println("猎狗在跑");
    }
}

//通过用 InvocationHandler 来封装最终被调用者，实现功能增强
class MyInvocationHandle implements InvocationHandler {
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("方法执行前");

        method.invoke(target, args);

        System.out.println("方法执行后");

        return null;
    }
}

//生产代理对象的工厂
class MyProxyFactory {
    public static Object getProxy(Object target) {
        MyInvocationHandle handle = new MyInvocationHandle();
        handle.setTarget(target);
        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handle);
        return proxy;
    }
}

public class ProxyDemo {
    public static void main(String[] args) {

        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");

        IDog dog = new GunDog();
        IDog proxy = (IDog) MyProxyFactory.getProxy(dog);
        proxy.run();
    }

}